<template>
  <div>
    <Draggable v-model="localList" item-key="id" handle=".drag-handle" animation="300">
      <template #item="{ element, index }">
        <div class="flex items-center gap-4 mb-4 p-4 border rounded">
          <span class="drag-handle cursor-move mr-2 text-xl">☰</span>

          <!-- 上传图片 -->
          <Upload
            :file-list="element.fileList"
            list-type="picture-card"
            :max-count="1"
            :api="api/user/upload/one"
            :show-upload-list="false"
            class="imgtext-uploader"
            :custom-request="({ onSuccess }) => onSuccess && onSuccess()"
            @change="(e) => onUploadChange(e, index)"
          >
            <img v-if="element.image" :src="element.image" alt="image" />
            <div v-else>
             <Icon icon="ri:add-line" />
            
            </div>
          </Upload>

          <!-- 输入文字 -->
          <input v-model="element.text" placeholder="请输入文字"  />

          <!-- 删除按钮 -->
          <span class="anticon" @click="remove(index)"><Icon icon="ri:delete-bin-line" /></span>
          
       
        </div>
      </template>
    </Draggable>

    <!-- 添加按钮 -->
    <Button type="dashed" block @click="add">
       添加图文
    </Button>
  </div>
</template>

<script setup>
import Icon from '#/components/Icons';
import {
  Upload,
  Input,
  Button
} from 'ant-design-vue';
import Draggable from 'vuedraggable';
import { ref } from 'vue';
import { h } from 'vue';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  defaultValue: {
    type: Array,
    default: () => [],
  },
});
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  defaultValue: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(['update:modelValue']);

const localList = ref([]);



// 添加新项
const add = () => {
  localList.value.push({
    id: Date.now() + Math.random(), // 添加唯一 ID
    image: '',
    text: '',
    fileList: [],
  });
  emit('update:modelValue', [...localList.value]);
};

// 删除项
const remove = (index) => {
  localList.value.splice(index, 1);
  emit('update:modelValue', [...localList.value]);
};

// 上传变化
const onUploadChange = (e, index) => {
  const fileUrl = e.file?.url || '';
  localList.value[index].image = fileUrl;
  localList.value[index].fileList = e.fileList;
  emit('update:modelValue', [...localList.value]);
};


</script>

<style scoped>
.drag-handle {
  cursor: move;
}
.imgtext-uploader  {
  :deep(.ant-upload) {
    width: 40px !important;
    height: 40px !important;
  }
}
</style>
